package com.bamboo.framework.framework.security.config;

import com.alibaba.fastjson.JSON;
import com.bamboo.framework.common.enums.Status;
import com.bamboo.framework.common.format.ReturnMsg;
import com.bamboo.framework.framework.redis.util.RedisUtil;
import com.bamboo.framework.framework.security.entity.Menu;
import com.bamboo.framework.framework.security.entity.User;
import com.bamboo.framework.framework.security.service.IMenuService;
import com.bamboo.framework.framework.security.util.SecurityUtil;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private IMenuService iMenuService;

    @Value("${bamboo.user.time-out-max}")
    private Long timeOut;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        String token = UUID.randomUUID().toString();

        //添加登陆用户到redis
        User user = SecurityUtil.getCurrentUser();
        List<Menu> menus = iMenuService.getMenusByRoles(user.getRoles());
        user.setMenus(menus);

        redisUtil.addObject( token,user,timeOut);

        response.getWriter().write(JSON.toJSONString(new ReturnMsg(Status.SUCCESS,token)));
    }
}

